package com.tengyun.middleplatform.trade.etl.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tengyun.middleplatform.trade.etl.bo.*;
import com.tengyun.middleplatform.trade.etl.enums.OrderSourceEnum;
import com.tengyun.middleplatform.trade.etl.mapper.chengxuan.ChengxuanOrdersMapper;
import com.tengyun.middleplatform.trade.etl.mapper.merchant.MerchantMapper;
import com.tengyun.middleplatform.trade.etl.mapper.order.OrdersMapper;
import com.tengyun.middleplatform.trade.etl.mapper.result.TradingOrderCouponMapper;
import com.tengyun.middleplatform.trade.etl.mapper.result.TradingOrderPayMapper;
import com.tengyun.middleplatform.trade.etl.mapper.result.TradingOrderRefundMapper;
import com.tengyun.middleplatform.trade.etl.mapper.result.TradingPlatformOrderMapper;
import com.tengyun.middleplatform.trade.etl.mapper.settlement.CouponBillMapper;
import com.tengyun.middleplatform.trade.etl.model.merchant.Merchant;
import com.tengyun.middleplatform.trade.etl.model.order.Orders;
import com.tengyun.middleplatform.trade.etl.model.result.*;
import com.tengyun.middleplatform.trade.etl.model.settlement.CouponBill;
import com.tengyun.middleplatform.trade.etl.service.IDataHandleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: likailun
 * @Description: 数据清洗服务
 * @Date: create in 2022/2/23 5:04 下午
 */
@Service
@Slf4j
public class IDataHandleServiceImpl implements IDataHandleService {

    @Resource
    private ChengxuanOrdersMapper chengxuanOrdersMapper;
    @Resource
    private TradingPlatformOrderMapper tradingPlatformOrderMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private TradingOrderPayMapper tradingOrderPayMapper;
    @Resource
    private TradingOrderRefundMapper tradingOrderRefundMapper;
    @Resource
    private CouponBillMapper couponBillMapper;
    @Resource
    private TradingOrderCouponMapper tradingOrderCouponMapper;
    @Resource
    private MerchantMapper merchantMapper;

    @Override
    public void currentDayData(LocalDate today) {
        // 获取前一天时间
        if (today == null) {
            today = LocalDate.now().minusDays(1);
        }
        LocalDateTime start = LocalDateTime.of(today.getYear(), today.getMonth(), today.getDayOfMonth(), 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(today.getYear(), today.getMonth(), today.getDayOfMonth(), 23, 59, 59);
        log.info("取数时间：{}至{}", start, end);
        // 清空数据先
        this.clearByStatisticsDate(today);

        this.orderDetailed(start, end);
        this.chengxuanOrderDetailed(start, end);
        this.getCouponOrder(start, end);

        // 结果数据
        List<TradingPlatformOrder> tradingPlatformOrders = new ArrayList<>();

        // -------------------------------------------交易中台数据处理
        // 支付
        List<OrdersMerchantSourceBO> midPay = tradingOrderPayMapper.queryOrderPayGroup(start, end);
        // 退款
        List<OrdersMerchantSourceBO> midRefund = tradingOrderRefundMapper.queryOrderRefundGroup(start, end);
        if (!CollectionUtils.isEmpty(midPay)) {
            for (OrdersMerchantSourceBO bo : midPay) {
                TradingPlatformOrder tradingPlatformOrder = new TradingPlatformOrder();
                tradingPlatformOrder.setFtime(start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                tradingPlatformOrder.setScene(bo.getOrderSource());
                tradingPlatformOrder.setOrderChannel(bo.getOrderScene());
                if (Arrays.asList(OrderSourceEnum.BUS_TICKET.getCode(), OrderSourceEnum.HOTEL.getCode()).contains(bo.getOrderSource())) {
                    tradingPlatformOrder.setOrderQuantity(new BigDecimal(bo.getOrderCount()));
                    tradingPlatformOrder.setPayNum(new BigDecimal(bo.getOrderCount()));
                } else {
                    tradingPlatformOrder.setOrderQuantity(new BigDecimal(bo.getSubOrderCount()));
                    tradingPlatformOrder.setPayNum(new BigDecimal(bo.getSubOrderCount()));
                }
                tradingPlatformOrder.setRefundNum(new BigDecimal(0));
                tradingPlatformOrder.setRefundAmount(new BigDecimal(0));
                tradingPlatformOrder.setMaterialCode(bo.getProductCode());
                tradingPlatformOrder.setMaterialName(bo.getProductName());
                tradingPlatformOrder.setExtend1(bo.getTradeInfo());
                tradingPlatformOrder.setExtend2(bo.getOrderChannel());
                // 判断是否有退款
                if (!CollectionUtils.isEmpty(midRefund)) {
                    // 退款金额
                    midRefund.stream().filter(r -> r.getMerchantCode().equals(bo.getMerchantCode()) && r.getOrderScene().equals(bo.getOrderScene())
                            && r.getOrderSource().equals(bo.getOrderSource()) && r.getSystemSource().equals(bo.getSystemSource())).findFirst().ifPresent(r -> {
                        // 退款订单数
                        tradingPlatformOrder.setRefundNum(new BigDecimal(r.getRefundCount()));
                        // 退款总金额
                        tradingPlatformOrder.setRefundAmount(new BigDecimal(r.getSumRefundAmount()));
                    });
                }
                // 有效单量
                tradingPlatformOrder.setEffectiveOrderNum(tradingPlatformOrder.getPayNum().subtract(tradingPlatformOrder.getRefundNum()));
                tradingPlatformOrder.setOrderAmount(new BigDecimal(bo.getSumOrderAmount()));
                // 交易金额，扣除优惠券
                tradingPlatformOrder.setTransactionAmount(new BigDecimal(bo.getSumFinallyCartAmount()));
                // GMV
                tradingPlatformOrder.setTradingSuccessAmount(new BigDecimal(bo.getSumOrderAmount()).subtract(tradingPlatformOrder.getRefundAmount()));
                tradingPlatformOrder.setBusniessCode(bo.getMerchantCode());
                tradingPlatformOrder.setBusniessName(bo.getMerchantName());
                tradingPlatformOrder.setTradingSuccessGross(tradingPlatformOrder.getPayNum().subtract(tradingPlatformOrder.getRefundNum()).toString());
                tradingPlatformOrder.setSystemSource(bo.getSystemSource());
                tradingPlatformOrders.add(tradingPlatformOrder);
            }
        }
        if (!CollectionUtils.isEmpty(midRefund)) {
            // 只有退款，没有支付的商品
            for (OrdersMerchantSourceBO bo : midRefund) {
                boolean hasPay = false;
                if (!CollectionUtils.isEmpty(midPay)) {
                    hasPay = midPay.stream().anyMatch(r -> r.getMerchantCode().equals(bo.getMerchantCode()) && r.getOrderScene().equals(bo.getOrderScene())
                            && r.getOrderSource().equals(bo.getOrderSource()));
                }
                if (CollectionUtils.isEmpty(midPay) || !hasPay) {
                    // 只有退款，没有支付
                    TradingPlatformOrder tradingPlatformOrder = new TradingPlatformOrder();
                    tradingPlatformOrder.setFtime(start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    tradingPlatformOrder.setScene(bo.getOrderSource());
                    tradingPlatformOrder.setOrderChannel(bo.getOrderScene());
                    tradingPlatformOrder.setOrderQuantity(new BigDecimal(0));
                    tradingPlatformOrder.setPayNum(new BigDecimal(0));
                    /*if(bo.getOrderSource().equals(OrderSourceEnum.BUS_TICKET.getCode())){
                        // 如果是汽车票，订单数量使用总订单统计
                    }*/
                    // 判断是否有退款
                    tradingPlatformOrder.setRefundNum(new BigDecimal(bo.getRefundCount()));
                    tradingPlatformOrder.setRefundAmount(new BigDecimal(bo.getSumRefundAmount()));
                    tradingPlatformOrder.setMaterialCode(bo.getProductCode());
                    tradingPlatformOrder.setMaterialName(bo.getProductName());
                    tradingPlatformOrder.setExtend1(bo.getTradeInfo());
                    tradingPlatformOrder.setExtend2(bo.getOrderChannel());
                    // 有效单量
                    tradingPlatformOrder.setEffectiveOrderNum(tradingPlatformOrder.getPayNum().subtract(tradingPlatformOrder.getRefundNum()));
                    tradingPlatformOrder.setOrderAmount(new BigDecimal(0));
                    // 交易金额，扣除优惠券
                    tradingPlatformOrder.setTransactionAmount(new BigDecimal(0));
                    // GMV
                    tradingPlatformOrder.setTradingSuccessAmount(new BigDecimal(0).subtract(new BigDecimal(bo.getSumRefundAmount())));
                    tradingPlatformOrder.setBusniessCode(bo.getMerchantCode());
                    tradingPlatformOrder.setBusniessName(bo.getMerchantName());
                    tradingPlatformOrder.setTradingSuccessGross(tradingPlatformOrder.getPayNum().subtract(tradingPlatformOrder.getRefundNum()).toString());
                    tradingPlatformOrder.setSystemSource(bo.getSystemSource());
                    tradingPlatformOrders.add(tradingPlatformOrder);
                }
            }
        }

        // -------------------------------------------诚选数据处理
        // 支付
        List<OrdersMerchantSourceBO> cxPay = tradingOrderPayMapper.queryChengxuanOrderPay(start, end);
        // 退款
        List<OrdersMerchantSourceBO> cxRefund = tradingOrderRefundMapper.queryChengxuanOrderRefund(start, end);
        if (!CollectionUtils.isEmpty(cxPay)) {
            for (OrdersMerchantSourceBO bo : cxPay) {
                log.info("诚选支付；{}", JSON.toJSONString(bo));
                TradingPlatformOrder tradingPlatformOrder = new TradingPlatformOrder();
                tradingPlatformOrder.setFtime(start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                tradingPlatformOrder.setScene("cx");
                tradingPlatformOrder.setOrderChannel(bo.getOrderScene());
                tradingPlatformOrder.setOrderQuantity(new BigDecimal(bo.getOrderCount()));
                tradingPlatformOrder.setPayNum(new BigDecimal(bo.getOrderCount()));
                tradingPlatformOrder.setRefundNum(new BigDecimal(0));
                tradingPlatformOrder.setRefundAmount(new BigDecimal(0));
                tradingPlatformOrder.setMaterialCode(bo.getProductCode() != null ? bo.getProductCode().toString() : "");
                tradingPlatformOrder.setMaterialName(bo.getProductName());
                // 判断是否有退款
                if (!CollectionUtils.isEmpty(cxRefund)) {
                    // 退款金额
                    cxRefund.stream().filter(r -> r.getMerchantCode().equals(bo.getMerchantCode()) && r.getOrderScene().equals(bo.getOrderScene())
                            && r.getSystemSource().equals(bo.getSystemSource())).findFirst().ifPresent(r -> {
                        // 退款订单数
                        tradingPlatformOrder.setRefundNum(new BigDecimal(r.getRefundCount()));
                        // 退款总金额
                        tradingPlatformOrder.setRefundAmount(new BigDecimal(r.getSumRefundAmount()));
                    });
                }
                // 有效单量
                tradingPlatformOrder.setEffectiveOrderNum(tradingPlatformOrder.getPayNum().subtract(tradingPlatformOrder.getRefundNum()));
                tradingPlatformOrder.setOrderAmount(new BigDecimal(bo.getSumOrderAmount()));
                // 交易金额，扣除优惠券
                tradingPlatformOrder.setTransactionAmount(new BigDecimal(bo.getSumFinallyCartAmount()));
                // GMV
                tradingPlatformOrder.setTradingSuccessAmount(tradingPlatformOrder.getOrderAmount().subtract(tradingPlatformOrder.getRefundAmount()));
                tradingPlatformOrder.setBusniessCode(bo.getMerchantCode() != null ? bo.getMerchantCode().toString() : "");
                tradingPlatformOrder.setBusniessName(bo.getMerchantName());
                tradingPlatformOrder.setTradingSuccessGross(tradingPlatformOrder.getPayNum().subtract(tradingPlatformOrder.getRefundNum()).toString());
                tradingPlatformOrder.setSystemSource(bo.getSystemSource());
                tradingPlatformOrders.add(tradingPlatformOrder);
            }
        }
        if (!CollectionUtils.isEmpty(cxRefund)) {
            // 只有退款，没有支付的商品
            for (OrdersMerchantSourceBO bo : cxRefund) {
                log.info("诚选退款；{}", JSON.toJSONString(bo));
                boolean hasPay = false;
                if (!CollectionUtils.isEmpty(cxPay)) {
                    hasPay = cxPay.stream().anyMatch(r -> null != r.getMerchantCode() && r.getMerchantCode().equals(bo.getMerchantCode())
                            && !StringUtils.isEmpty(r.getOrderScene()) && r.getOrderScene().equals(bo.getOrderScene()));
                }
                if (CollectionUtils.isEmpty(cxPay) || !hasPay) {
                    // 只有退款，没有支付
                    TradingPlatformOrder tradingPlatformOrder = new TradingPlatformOrder();
                    tradingPlatformOrder.setFtime(start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    tradingPlatformOrder.setScene("cx");
                    tradingPlatformOrder.setOrderChannel(bo.getOrderScene());
                    tradingPlatformOrder.setOrderQuantity(new BigDecimal(0));
                    tradingPlatformOrder.setPayNum(new BigDecimal(0));
                    tradingPlatformOrder.setMaterialCode(bo.getProductCode() != null ? bo.getProductCode().toString() : "");
                    tradingPlatformOrder.setMaterialName(bo.getProductName());
                    // 判断是否有退款
                    if (!CollectionUtils.isEmpty(cxRefund)) {
                        tradingPlatformOrder.setRefundNum(new BigDecimal(bo.getRefundCount()));
                        tradingPlatformOrder.setRefundAmount(new BigDecimal(bo.getSumRefundAmount()));

                    }
                    // 有效单量
                    tradingPlatformOrder.setEffectiveOrderNum(tradingPlatformOrder.getPayNum().subtract(tradingPlatformOrder.getRefundNum()));
                    tradingPlatformOrder.setOrderAmount(new BigDecimal(0));
                    // 交易金额，扣除优惠券
                    tradingPlatformOrder.setTransactionAmount(new BigDecimal(0));
                    // GMV
                    tradingPlatformOrder.setTradingSuccessAmount(new BigDecimal(0).subtract(tradingPlatformOrder.getRefundAmount()));
                    tradingPlatformOrder.setBusniessCode(bo.getMerchantCode() != null ? bo.getMerchantCode().toString() : "");
                    tradingPlatformOrder.setBusniessName(bo.getMerchantName());
                    tradingPlatformOrder.setTradingSuccessGross(tradingPlatformOrder.getPayNum().subtract(tradingPlatformOrder.getRefundNum()).toString());
                    tradingPlatformOrder.setSystemSource(bo.getSystemSource());
                    tradingPlatformOrders.add(tradingPlatformOrder);
                }
            }
        }
        if (!CollectionUtils.isEmpty(tradingPlatformOrders)) {
            tradingPlatformOrderMapper.saveBatch(tradingPlatformOrders);
        }
    }
    /**
     * 清空数据
     *
     * @param statisticsDate 统计日期
     */
    private void clearByStatisticsDate(LocalDate statisticsDate) {
        tradingOrderPayMapper.delete(new QueryWrapper<TradingOrderPay>().eq("statistics_date", statisticsDate));
        tradingOrderRefundMapper.delete(new QueryWrapper<TradingOrderRefund>().eq("statistics_date", statisticsDate));
        tradingOrderCouponMapper.delete(new QueryWrapper<TradingOrderCoupon>().eq("statistics_date", statisticsDate));
        LocalDateTime start = LocalDateTime.of(statisticsDate.getYear(), statisticsDate.getMonth(), statisticsDate.getDayOfMonth(), 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(statisticsDate.getYear(), statisticsDate.getMonth(), statisticsDate.getDayOfMonth(), 23, 59, 59);
        tradingPlatformOrderMapper.delete(new QueryWrapper<TradingPlatformOrder>().between("ftime", start, end));
    }

    /**
     * 订单明细处理
     *
     * @param start 开始时间
     * @param end   结束时间
     */
    private void orderDetailed(LocalDateTime start, LocalDateTime end) {
        Integer midOrderCount = ordersMapper.queryOrderPayCount(start, end);
        // 每次处理1000条
        int pageSize = 1000;
        if (midOrderCount > 0) {
            int loopCount = (int) Math.ceil(new BigDecimal(midOrderCount).divide(new BigDecimal(1000)).doubleValue());
            if (loopCount == 0) {
                loopCount = 1;
            }
            for (int i = 0; i < loopCount; i++) {
                List<OrdersPayBO> ordersPayBOS = ordersMapper.queryOrderPay(start, end, i * pageSize, pageSize);
                if (CollectionUtils.isEmpty(ordersPayBOS)) {
                    continue;
                }
                List<TradingOrderPay> tradingOrderPays = new ArrayList<>();
                for (OrdersPayBO ordersPayBO : ordersPayBOS) {
                    TradingOrderPay tradingOrderPay = new TradingOrderPay();
                    BeanUtils.copyProperties(ordersPayBO, tradingOrderPay);
                    tradingOrderPay.setSubOrderPayAmount(ordersPayBO.getPayAmount());
                    tradingOrderPay.setCreateOrderTime(ordersPayBO.getCreateOrderTime());
                    tradingOrderPay.setCreatedTime(LocalDateTime.now());
                    tradingOrderPay.setStatisticsDate(start.toLocalDate());
                    if (StringUtils.isEmpty(tradingOrderPay.getOriginalOrderId())) {
                        tradingOrderPay.setOriginalOrderId("0");
                    }
                    tradingOrderPays.add(tradingOrderPay);
                }
                this.tradeInfoConvert(tradingOrderPays);
                tradingOrderPayMapper.saveBatch(tradingOrderPays);
            }
        }

        Integer midRefundCount = ordersMapper.queryOrderRefundCount(start, end);
        // 每次处理1000条
        if (midRefundCount > 0) {
            int loopCount = (int) Math.ceil(new BigDecimal(midRefundCount).divide(new BigDecimal(1000)).doubleValue());
            if (loopCount == 0) {
                loopCount = 1;
            }
            for (int i = 0; i < loopCount; i++) {
                List<OrdersRefundBO> ordersRefundBOS = ordersMapper.queryOrderRefund(start, end, i * pageSize, pageSize);
                if (CollectionUtils.isEmpty(ordersRefundBOS)) {
                    continue;
                }
                List<TradingOrderRefund> tradingOrderRefunds = new ArrayList<>();
                for (OrdersRefundBO ordersRefundBO : ordersRefundBOS) {
                    TradingOrderRefund tradingOrderRefund = new TradingOrderRefund();
                    BeanUtils.copyProperties(ordersRefundBO, tradingOrderRefund);
                    tradingOrderRefund.setCreateTime(LocalDateTime.now());
                    tradingOrderRefund.setStatisticsDate(start.toLocalDate());
                    if (StringUtils.isEmpty(tradingOrderRefund.getOriginalOrderId())) {
                        tradingOrderRefund.setOriginalOrderId("0");
                    }
                    tradingOrderRefunds.add(tradingOrderRefund);
                }
                this.tradeInfoConvert(tradingOrderRefunds);
                tradingOrderRefundMapper.saveBatch(tradingOrderRefunds);
            }
        }
    }

    /**
     * 转换trade_info信息
     *
     * @param records
     */
    private void tradeInfoConvert(List<? extends TradingBase> records) {
        if (CollectionUtils.isEmpty(records)) {
            return;
        }
        List<String> orderIds = records.stream().filter(item -> item.getOrderSource().equals(OrderSourceEnum.TRAFFIC.getCode())
                && !StringUtils.isEmpty(item.getOriginalOrderId()) && item.getOriginalOrderId().length()
                > 1).map(TradingBase::getOriginalOrderId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(orderIds)) {
            return;
        }
        List<Orders> orders = ordersMapper.selectList(new QueryWrapper<Orders>().in("order_id", orderIds));
        orders.forEach(item -> records.stream().filter(o -> o.getOriginalOrderId().equals(item.getOrderId())).findFirst().ifPresent(f -> f.setTradeInfo(item.getTradeInfo())));
    }

    /**
     * 诚选——订单明细处理
     *
     * @param start 开始时间
     * @param end   结束时间
     */
    private void chengxuanOrderDetailed(LocalDateTime start, LocalDateTime end) {
        Integer cxOrderCount = chengxuanOrdersMapper.queryChengxuanOrderPayDetailCount(start, end);
        // 每次处理1000条
        int pageSize = 1000;
        if (cxOrderCount > 0) {
            int loopCount = cxOrderCount / 1000;
            if (loopCount == 0) {
                loopCount = 1;
            }
            for (int i = 0; i < loopCount; i++) {
                List<ChengxuanOrdersPayBO> ordersPayBOS = chengxuanOrdersMapper.queryChengxuanOrderPayDetail(start, end, i * pageSize, pageSize);
                if (CollectionUtils.isEmpty(ordersPayBOS)) {
                    continue;
                }
                List<TradingOrderPay> tradingOrderPays = new ArrayList<>();
                ordersPayBOS.stream().collect(Collectors.groupingBy(ChengxuanOrdersPayBO::getOrderId)).forEach((orderId, subOrders) -> {
                    TradingOrderPay tradingOrderPay = new TradingOrderPay();
                    BeanUtils.copyProperties(subOrders.get(0), tradingOrderPay);
                    tradingOrderPay.setCreateOrderTime(subOrders.get(0).getCreateOrderTime());
                    tradingOrderPay.setCreatedTime(LocalDateTime.now());
                    tradingOrderPay.setStatisticsDate(start.toLocalDate());
                    tradingOrderPay.setIsCoupon(subOrders.get(0).getDiscount() != null && subOrders.get(0).getDiscount().compareTo(BigDecimal.ZERO) > 0);
                    tradingOrderPay.setSubOrderPayAmount(subOrders.get(0).getPayAmount().multiply(new BigDecimal(100)).intValue());
                    tradingOrderPay.setSubOrderAmount(subOrders.get(0).getSubOrderAmount().multiply(new BigDecimal(100)).intValue());
                    tradingOrderPay.setDiscount(subOrders.stream().mapToInt(item -> item.getDiscount().multiply(new BigDecimal(100)).intValue()).sum());
                    tradingOrderPay.setPlatformDiscount(subOrders.get(0).getPlatformDiscount().multiply(new BigDecimal(100)).intValue());
                    tradingOrderPay.setProductCost(subOrders.stream().mapToInt(item -> item.getProductCost().multiply(new BigDecimal(100)).intValue()).sum());
                    tradingOrderPay.setOriginalOrderId("");
                    tradingOrderPay.setSystemSource("CHENGXUAN");
                    tradingOrderPay.setProductName(subOrders.stream().map(ChengxuanOrdersPayBO::getProductName).collect(Collectors.joining(",")));
                    if (!StringUtils.isEmpty(tradingOrderPay.getOrderScene()) && tradingOrderPay.getOrderScene().equals("wxpayinwxapp")) {
                        tradingOrderPay.setOrderScene("miniapp");
                        tradingOrderPay.setPayScene("miniapp");
                    }
                    if (!StringUtils.isEmpty(tradingOrderPay.getOrderScene()) && tradingOrderPay.getOrderScene().equals("wxpay")) {
                        tradingOrderPay.setOrderScene("app");
                        tradingOrderPay.setPayScene("APP");
                    }
                    if (StringUtils.isEmpty(tradingOrderPay.getMerchantCode())) {
                        tradingOrderPay.setMerchantCode("");
                    }
                    if (StringUtils.isEmpty(tradingOrderPay.getMerchantName())) {
                        tradingOrderPay.setMerchantName("");
                    }
                    if (StringUtils.isEmpty(tradingOrderPay.getProductCode())) {
                        tradingOrderPay.setProductCode("");
                    }
                    if (StringUtils.isEmpty(tradingOrderPay.getProductName())) {
                        tradingOrderPay.setProductName("");
                    }
                    tradingOrderPay.setPayWay("wechat");
                    tradingOrderPays.add(tradingOrderPay);
                });
                tradingOrderPayMapper.saveBatch(tradingOrderPays);
            }
        }

        Integer midRefundCount = chengxuanOrdersMapper.queryChengxuanOrderRefundDetailCount(start, end);
        // 每次处理1000条
        if (midRefundCount > 0) {
            int loopCount = midRefundCount / 1000;
            if (loopCount == 0) {
                loopCount = 1;
            }
            for (int i = 0; i < loopCount; i++) {
                List<ChengxuanOrdersRefundBO> ordersRefundBOS = chengxuanOrdersMapper.queryChengxuanOrderRefundDetail(start, end, i * pageSize, pageSize);
                if (CollectionUtils.isEmpty(ordersRefundBOS)) {
                    continue;
                }
                List<TradingOrderRefund> tradingOrderRefunds = new ArrayList<>();
                for (ChengxuanOrdersRefundBO ordersRefundBO : ordersRefundBOS) {
                    TradingOrderRefund tradingOrderRefund = new TradingOrderRefund();
                    BeanUtils.copyProperties(ordersRefundBO, tradingOrderRefund);
                    tradingOrderRefund.setCreateTime(LocalDateTime.now());
                    tradingOrderRefund.setStatisticsDate(start.toLocalDate());
                    tradingOrderRefund.setSubOrderAmount(ordersRefundBO.getSubOrderAmount().multiply(new BigDecimal(100)).intValue());
                    tradingOrderRefund.setSubOrderPayAmount(ordersRefundBO.getSubOrderPayAmount().multiply(new BigDecimal(100)).intValue());
                    tradingOrderRefund.setRefundAmount(ordersRefundBO.getRefundAmount().multiply(new BigDecimal(100)).intValue());
                    tradingOrderRefund.setRefundApplyAmount(ordersRefundBO.getRefundApplyAmount().multiply(new BigDecimal(100)).intValue());
                    tradingOrderRefund.setOriginalOrderId("");
                    tradingOrderRefund.setSystemSource("CHENGXUAN");
                    tradingOrderRefund.setPlatformDiscount(0);
                    if (!StringUtils.isEmpty(tradingOrderRefund.getOrderScene()) && tradingOrderRefund.getOrderScene().equals("wxpayinwxapp")) {
                        tradingOrderRefund.setOrderScene("miniapp");
                    }
                    if (!StringUtils.isEmpty(tradingOrderRefund.getOrderScene()) && tradingOrderRefund.getOrderScene().equals("wxpay")) {
                        tradingOrderRefund.setOrderScene("app");
                    }
                    if (StringUtils.isEmpty(tradingOrderRefund.getMerchantCode())) {
                        tradingOrderRefund.setMerchantCode("");
                    }
                    if (StringUtils.isEmpty(tradingOrderRefund.getMerchantName())) {
                        tradingOrderRefund.setMerchantName("");
                    }
                    if (StringUtils.isEmpty(tradingOrderRefund.getProductCode())) {
                        tradingOrderRefund.setProductCode("");
                    }
                    if (StringUtils.isEmpty(tradingOrderRefund.getProductName())) {
                        tradingOrderRefund.setProductName("");
                    }
                    tradingOrderRefund.setPayWay("wechat");
                    tradingOrderRefunds.add(tradingOrderRefund);
                }
                tradingOrderRefundMapper.saveBatch(tradingOrderRefunds);
            }
        }
    }

    /**
     * 查询优惠券订单信息
     *
     * @param start 创建订单时间开始
     * @param end   创建订单时间结束
     */
    private void getCouponOrder(LocalDateTime start, LocalDateTime end) {
        Integer count = ordersMapper.queryCouponOrderCount(start, end);
        if (count > 0) {
            int loopCount = (int) Math.ceil(new BigDecimal(count).divide(new BigDecimal(1000)).doubleValue());
            if (loopCount == 0) {
                loopCount = 1;
            }
            for (int i = 0; i < loopCount; i++) {
                List<TradingOrderCoupon> orders = ordersMapper.queryCouponOrder(start, end, i * 1000, 1000);
                if (CollectionUtils.isEmpty(orders)) {
                    continue;
                }
                orders.forEach(o -> {
                    o.setCreatedTime(LocalDateTime.now());
                    o.setStatisticsDate(start.toLocalDate());
                    o.setVipDiscount(0);
                });
                List<String> channelCouponOrderIds = orders.stream().map(TradingOrderCoupon::getOrderId).collect(Collectors.toList());
                List<CouponBill> channelCouponOrders = couponBillMapper.selectList(new QueryWrapper<CouponBill>().in("order_id", channelCouponOrderIds).eq("data_status", 1));
                if (!CollectionUtils.isEmpty(channelCouponOrders)) {
                    channelCouponOrders.forEach(c -> orders.stream().filter(o -> o.getOrderId().equals(c.getOrderId())).forEach(o -> {
                        if(c.getCouponType().equals(1)){
                            o.setChannelCouponCode(c.getCouponNo());
                            o.setChannelCouponName(c.getMinimum());
                            o.setChannelDiscount(c.getChannelDiscount());
                            o.setCouponBatchId(c.getCouponBatchId());
                            o.setChannelAvailableStartTime(c.getAvailableStartTime());
                            o.setChannelAvailableEndTime(c.getAvailableEndTime());
                            o.setVipDiscount(c.getVipDiscount()==null?0:c.getVipDiscount());
                        }else if(c.getCouponType().equals(2)){
                            o.setCouponCode(c.getCouponNo());
                            o.setCouponBatchId(c.getCouponBatchId());
                            o.setCouponName(c.getMinimum());
                            o.setPlatformDiscount(c.getPlatformDiscount());
                            o.setPlatformAvailableStartTime(c.getAvailableStartTime());
                            o.setPlatformAvailableEndTime(c.getAvailableEndTime());
                            o.setVipDiscount(c.getVipDiscount()==null?0:c.getVipDiscount());
                        }
                    }));
                }
                tradingOrderCouponMapper.saveBatch(orders);
            }
        }
    }
}
